from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthUser
from oauth.utils import generate_save_user_token
from . import serializers

class QQAuthURLView(APIView):
    '''提供QQ登录页面网站
        https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
    '''
    def get(self,request):
        #next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next=request.query_params.get('next')
        if not next:
            next='/'

        #获取QQ登录页面网站
        oauth=OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        login_url=oauth.get_qq_url()

        return Response({"login_url":login_url})


class QQAuthUserView(GenericAPIView):

    serializer_class =serializers.QQAuthUserSerializer
    '''QQ登录用户的信息绑定视图'''
    def get(self,request):
        #1.获取code授权码
        code=request.query_params.get('code')
        if code is None:
            return Response({'message':'缺少code授权码'},status=status.HTTP_400_BAD_REQUEST)

        # 登陆成功以后的跳转地址
        next = request.query_params.get("state")
        if next is None:
            # 如果没有设置，则默认为域名根目录
            next = "/"

        #2.获取QQ登录的access_token
        #使用qqLoginTool工具包里面的方法生成url
        oauth=OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        access_token=oauth.get_access_token(code)
        #3.根据access_token获取oppenID
        openid=oauth.get_open_id(access_token)
        print(111111, openid)

        #4.根据openID到数据库中查找是否有对应的QQ登录用户
        try:
            #表示不是第一次使用QQ登录，直接保存登录状态
            #【先做状态保存，先到数据表中添加一条记录】
            oauth_user=OAuthUser.objects.get(openid=openid)
            print(oauth_user)
        except OAuthUser.DoesNotExist:
            #没有找到openID对应的用户，则表示第一次使用QQ登录
            #让用户进行身份绑定
            return Response({
                #Itsdangrous生成的临时票据，里面隐藏了openid
                'access_token':generate_save_user_token(openid),
            })
        else:
            #如果openid已绑定没多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            #获取oauth_uesr关联的user
            user = oauth_user.user
            payload=jwt_payload_handler(user)
            token=jwt_encode_handler(payload)
            return Response({
                'token':token,
                'user_id':user.id,
                'username':user.username
            })


    def post(self,request):
        #获取序列化器对象【传递post数据】
        serializer=self.get_serializer(data=request.data)

        #校验数据
        serializer.is_valid(raise_exception=True)

        #调用了序列化器中的save()
        user=serializer.save()

        #5.返回登录状态jwt
        #如果openid已经绑定美多商城用户，直接生成JWTtoken,并返回
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 获取oauth_user关联的user
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })
